import React, { useState, useEffect, useRef } from 'react'
import { Avatar, Modal, Image, DatePicker, message, Space } from 'antd';
import { ModalForm, ProFormDateRangePicker, ProFormSelect, ProTable } from '@ant-design/pro-components';
import TheButton from "@/components/TheButton/index.jsx";
import moment from 'moment';
import { apiGetSpellTogetherPage, apiGetSpellTogetherEnd } from "@/api/spellTogether/index.js";
import { useNavigate } from "react-router-dom";
import {useWindowSize} from "@/utils/useWindowSize.js";

const { confirm } = Modal;
const { RangePicker } = DatePicker;

export default () => {
  const {width, height} = useWindowSize();
  const [tbScrollH, setTbScrollH] = useState('40vh');
  const [loadings, setLoadings] = useState([]);
  const navigate = useNavigate();
  const actionRef = useRef();
  const columns = [
    {
      title: "拼团活动",
      dataIndex: "query",
      key: "query",
      hideInTable: true,
      fieldProps: {
        placeholder: "请输入活动id/名称"
      }
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      hideInTable: true,
      valueType: 'select',
      valueEnum: {
        '': { text: '全部状态' },
        '未开始': { text: '未开始' },
        '进行中': { text: '进行中' },
        '已结束': { text: '已结束' },
      },
      initialValue: ''
    },
    {
      title: "活动id",
      dataIndex: "activityId",
      key: "activityId",
      hideInSearch: true,
    },
    {
      title: "活动名称",
      dataIndex: "activityName",
      key: "activityName",
      hideInSearch: true,
    },
    {
      title: "活动时间",
      dataIndex: "activityTime",
      key: "activityTime",
      hideInSearch: true,
      render: (text, render) => {
        return render.startTime + " ~ " + render.realityEndTime
      }
    },
    {
      title: "状态",
      dataIndex: "activityStatusEnum",
      key: "activityStatusEnum",
      hideInSearch: true
    },
    {
      title: "最近修改时间",
      dataIndex: "updateTime",
      key: "updateTime",
      hideInSearch: true,
    },
    {
      title: "操作",
      valueType: 'option',
      fixed: "right",
      render: (text, render, index) => {
        return (
          <Space>
            <TheButton haspermi={['spellTogether:list:view']} type={'link'} onClick={() => onView(render.activityId)}>查看</TheButton>
            {
              render.activityStatusEnum !== "已结束" && <>
                <TheButton haspermi={['spellTogether:list:edit']} type={'link'} onClick={() => onEdit(render.activityId)}>修改</TheButton>
                <TheButton haspermi={['spellTogether:list:end']} type={'link'} onClick={() => end(render.activityId,index)} loading={loadings[index]}>提前结束</TheButton>
              </>
            }
            {
              render.activityStatusEnum !== "未开始" && <TheButton haspermi={['spellTogether:list:data']} type={'link'} onClick={() => onResult(render.activityId)}>数据</TheButton>
            }
          </Space>
        );
      },
    },
  ]
  const [loading, setLoading] = useState(false);
  const end = (activityId,RowIndex) => {
    setLoadings((prevLoadings) => {
      const newLoadings = [...prevLoadings];
      newLoadings[RowIndex] = true;
      return newLoadings;
    });
    confirm({
      title: "提示",
      content: `提前关闭拼团活动可能导致正在购买的消费者无法正常下单，是否继续关闭？`,
      onOk: async () => {
        let res = await apiGetSpellTogetherEnd({ activityId })
        if (res.code === 0) {
          message.info("提前结束成功")
          actionRef.current.reload();
        }
        setLoadings((prevLoadings) => {
          const newLoadings = [...prevLoadings];
          newLoadings[RowIndex] = false;
          return newLoadings;
        });
      },
      onCancel: () => {
        setLoadings((prevLoadings) => {
          const newLoadings = [...prevLoadings];
          newLoadings[RowIndex] = false;
          return newLoadings;
        });
      }
    })
  }
  const onAdd = () => {
    navigate('/spellTogether/list/event', {
      state: {
        mode: "add"
      }
    })
  }
  const onEdit = (activityId) => {
    navigate('/spellTogether/list/event', {
      state: {
        mode: "edit",
        activityId
      }
    })
  }
  const onView = (activityId) => {
    navigate('/spellTogether/list/event', {
      state: {
        mode: "view",
        activityId
      }
    })
  }
  const onResult = (activityId) => {
    navigate('/spellTogether/list/result', {
      state: {
        mode: "result",
        activityId
      }
    })
  }

  useEffect(() => {
    if (height >= 1080){
      setTbScrollH('58vh')
    }else if(height < 1080 && height >= 960){
      setTbScrollH('52vh')
    }
  }, [])

  return <div>
    <ProTable
      actionRef={actionRef}
      scroll={{ x: "max-content", y: tbScrollH }}
      rowKey={(record) => record.activityId}
      bordered={true}
      options={false}
      columns={columns}
      pagination={{
        defaultPageSize: 10,
        position: ['bottomCenter'],
        showSizeChanger: false
      }}
      headerTitle={
        <TheButton haspermi={['spellTogether:list:add']} key="add" onClick={() => onAdd()}>新建拼团活动</TheButton>
      }
      request={async (params, sort, filter) => {
        // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
        // 如果需要转化参数可以在这里进行修改
        const res = await apiGetSpellTogetherPage({
          pageNo: params.current,
          pageSize: params.pageSize,
          ...params
        });

        return {
          data: res.data,
          // success 请返回 true，
          // 不然 table 会停止解析数据，即使有数据
          success: res.code === 0,
          // 不传会使用 data 的长度，如果是分页一定要传
          total: res.totalCount,
        };
      }}
      search={{
        optionRender: (searchConfig, formProps, dom) => {
          return dom.reverse()
        },
        collapsed: false,
        collapseRender: false
      }}
    />
  </div>
}
